<?php
// +----------------------------------------------------------------------
// | HkCms 推荐位管理
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2019 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------

namespace app\content\controller;

use common\controller\AdminBase;
use think\Db;

class Position extends AdminBase
{
	
    //推荐位列表
    public function index() {
        $data = Db::name('Position')->order(array('listorder' => 'ASC', 'posid' => 'DESC'))->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    //数据重建
    public function rebuilding() {

        $action = input('action', 0, 'intval');

        $posid = input('posid', 0, 'intval');

        if (empty($posid)) {

            $this->error('请指定需要进行重建数据的推荐位！');
        }

        $model = Db::name('PositionData');

        if ($action == 0) {//初始化

            $count = $model->where('posid',$posid)->count();

            $lun = ceil($count / 20);

            $_GET['lun'] = $lun;

            $_GET['count'] = $count;

            $_GET['action'] = 1;

            $_GET['i'] = 0;

            $_GET['posid'] = $posid;

            $this->assign('waitSecond', 100);

            $this->success('开始准备进行数据重建工作！', url('rebuilding', $_GET));

            exit;
        } else if ($action == 1) {

            $lun = input('lun', 1, 'intval');

            $i = input('i', 0, 'intval');

            $cid = input('cid', 0, 'intval');

            if ($i > $lun) {

                $this->success('数据重建完毕！', url('index'));

                exit;
            }

            $where = [

                'posid' => $posid, 

                'id' => array('GT', $cid)
            ];

            $dataList = $model->where($where)->order(array('id' => 'ASC'))->limit(20)->select();

            if (empty($dataList)) {

                $this->success('数据重建完毕！', url('index'));

                exit;
            }

            $modelList = hk_cache('Model');

            $modelField = hk_cache('ModelField');

            foreach ($dataList as $rs) {

                $modelid = $rs['modelid'];

                // $data = \app\content\model\Content::getInstance($modelid)->relation(true)->where(array('id' => $rs['id']))->find();

                /*---------------------------------------------------------*/
                $modelCache = hk_cache("Model");

                $tablename = $modelCache[$modelid]['tablename'];

                $data_1 = Db::name($tablename)->where('id',$rs['id'])->find();

                $data_2 = Db::name($tablename.'_data')->where('id',$rs['id'])->find();

                if ($data_1) {

                    $data = array_merge($data_1,$data_2);
                }
                /*---------------------------------------------------------*/

                if (!$modelList[$modelid] || !$modelField[$modelid]) {

                    continue;
                }

                // \app\content\model\Content::getInstance($modelid)->dataMerger($data);

                $textcontent = array();

                foreach ($modelField[$modelid] as $fieldInfo) {

                    $field = $fieldInfo['field'];

                    if ($fieldInfo['isposition']) {

                        $textcontent[$field] = $data[$field];
                    }
                }

                $textcontent['style'] = $data['style'] ? : '';

                $newsData = [

                    'id' => $rs['id'],

                    'catid' => $rs['catid'],

                    'modelid' => $modelid,

                    'thumb' => $textcontent['thumb'] ? 1 : 0,

                    'data' => serialize($textcontent),
                ];

                $model->where(array('posid' => $posid, 'id' => $rs['id'], 'catid' => $rs['catid'], 'modelid' => $modelid))->update($newsData);

                $cid = $rs['id'];
            }

            $i++;

            $_GET['lun'] = $lun;

            $_GET['i'] = $i;

            $_GET['cid'] = $cid;

            $_GET['posid'] = $posid;

            $_GET['action'] = $action;

            $jindu = round(($i / $lun) * 100, 3);

            $this->assign('waitSecond', 100);

            $this->success("数据重建中..总共<font color=\"#FF0000\">{$lun}</font>轮，当前第<font color=\"#FF0000\">{$i}</font>轮，进度：<font color=\"#FF0000\">{$jindu}%</font>", url('rebuilding', $_GET));
        }
    }

    //添加推荐位
    public function add() {

        if ( request()->isPOST() ) {

            $model = model('content/Position');

            // $_POST['info'] = array_merge($_POST['info'], array(config("TOKEN_NAME") => $_POST[config("TOKEN_NAME")]));
            $_POST['info'] = $_POST['info'];

            if ($model->positionAdd($_POST['info'])) {

                $this->success("添加成功！<font color=\"#FF0000\">请更新缓存！</font>", url("Content/Position/index"));
            } else {

                $this->error($model->error);
            }

        }

        $Model = hk_cache('Model');

        foreach ($Model as $k => $v) {

            if ($v['type'] == 0) {

                $modelinfo[$v['modelid']] = $v['name'];
            }
        }

        $this->assign('modelinfo', $modelinfo);

        return $this->fetch();
    }

    //编辑推荐位
    public function edit() {

        $model = model('content/Position');

        if ( request()->isPOST() ) {

            // $_POST['info'] = array_merge($_POST['info'], array(config("TOKEN_NAME") => $_POST[config("TOKEN_NAME")]));

            if ($model->positionSave($_POST['info'])) {

                $this->success('更新成功！<font color=\"#FF0000\">请更新缓存！</font>', url('index'));

            } else {

                $this->error($model->getError()? : '修改失败！');
            }
        }

        $posid = input('posid', 0, 'intval');

        $data = $model->where(array('posid' => $posid))->find()->toarray();

        if (!$data) {

            $this->error('该推荐位不存在！');
        }

        $Model = hk_cache('Model');

        foreach ($Model as $k => $v) {

            if ($v['type'] == 0) {

                $modelinfo[$v['modelid']] = $v['name'];
            }
        }

        $this->assign($data);

        $this->assign('modelinfo', $modelinfo);

        return $this->fetch();
    }

    //删除 推荐位
    public function delete() {

        $posid = input('posid', 0, 'intval');

        $model = model('content/Position');

        if ($model->positionDel($posid)) {

            $this->success('删除成功！<font color=\"#FF0000\">请更新缓存！</font>', url('content/Position/index'));

        } else {

            $this->error('删除失败');
        }
    }

    //排序
    public function public_item_listorder() {
        if ( request()->isPOST() ) {
            $db = db('PositionData');
            foreach ($_POST['listorders'] as $_k => $listorder) {
                $pos = array();
                $pos = explode('-', $_k);
                $db->where(array('id' => $pos[1], 'catid' => $pos[0], 'posid' => $_POST['posid']))->data(array('listorder' => $listorder))->update();
            }
            $this->success("排序更新成功！");
        } else {
            $this->error("请使用POST方式提交！");
        }
    }

    //信息管理
    public function item() 
    {
        if ( request()->isPOST() ) {

            if (!isset($_POST['items'])) {

                $this->error("没有信息被选择！");
            }

            $items = count($_POST['items']) > 0 ? $_POST['items'] : $this->error("没有信息被选择！");

            $db = model('content/PositionData');

            if (is_array($items)) {

                foreach ($items as $item) {
                    $_v = explode('-', $item);
                    $db->deleteItem((int) $_POST['posid'], (int) $_v[0], (int) $_v[1]);
                }
            }
            $this->success("移除成功！");
        } 

        $posid = input('posid', 0, 'intval');

        $db = model('PositionData');

        $where = array();

        $where['posid'] = $posid;

        $count = $db->where($where)->count();

        $page = $this->page($count, 20);

        $data = $db->where($where)->order(array("listorder" => "DESC", "id" => "DESC"))->limit($page->firstRow . ',' . $page->listRows)->select()->toarray();

        foreach ($data as $k => $v) {

            $data[$k]['data'] = unserialize($v['data']);

            $tab = ucwords(getModel(getCategory($v['catid'], 'modelid'), 'tablename'));

            $url = Db::name($tab)->where(array("id" => $v['id']))->value("url");

            $data[$k]['data']['url'] =  $url;

        }

        $this->assign("Page", $page->show())
                ->assign("data", $data)
                ->assign("posid", $posid)
                ->assign('menuReturn', array('url' => url('index'), 'name' => '返回推荐位管理'));

        return $this->fetch();
    }

    // //排序
    // public function public_item_listorder() {
    //     if (IS_POST) {
    //         $db = M('PositionData');
    //         foreach ($_POST['listorders'] as $_k => $listorder) {
    //             $pos = array();
    //             $pos = explode('-', $_k);
    //             $db->where(array('id' => $pos[1], 'catid' => $pos[0], 'posid' => $_POST['posid']))->data(array('listorder' => $listorder))->save();
    //         }
    //         $this->success("排序更新成功！");
    //     } else {
    //         $this->error("请使用POST方式提交！");
    //     }
    // }

    //信息管理编辑
    public function item_manage() 
    {
        $db = model('content/PositionData');

        if ( request()->isPOST() ) {

            if ($_POST['thumb']) {

                $_POST['data']['thumb'] = $_POST['thumb'];

                $_POST['thumb'] = 1;

            } else {

                $_POST['thumb'] = 0;
            }

            if ($db->positionEdit($_POST)) {

                $this->success("更新成功！");

            } else {

                $this->error("更新失败！");
            }
        }

        $id = input('get.id', 0, 'intval');

        $modelid = input('get.modelid', 0, 'intval');

        $posid = input('get.posid', 0, 'intval');

        $data = $db->where(array("id" => $id, "modelid" => $modelid, 'posid' => $posid))->find()->toarray();

        if (empty($data)) {

            $this->error("该信息不存在！");
        }

        $data['data'] = unserialize($data['data']);

        $this->assign($data);
        
        return $this->fetch();
        
    }

    ///推荐位添加栏目加载
    public function public_category_load() {

        $modelid = input('get.modelid', '', '');

        $modelidList = explode(',', $modelid);

        $result = hk_cache('Category');

        if (is_array($result)) {

            $categorys = array();

            foreach ($result as $r) {

                $r = getCategory($r['catid']);

                //过滤非普通栏目信息
                if ($r['type'] != 0) {

                    continue;
                }

                $categorys[$r['catid']] = $r['catname'];

                if ($r['child'] != 0) {

                    unset($categorys[$r['catid']]);
                }

                if (!empty($modelid) && !in_array($r['modelid'], $modelidList)) {

                    unset($categorys[$r['catid']]);
                }
            }
        }
        echo \libs\util\Form::checkbox($categorys, input('get.catid', 0, ''), 'name="info[catid][]"', '', 1);
    }

}